package com.ruoyi.system.service.impl;

import com.ruoyi.common.config.CloudConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.OssUtil;
import com.ruoyi.system.service.ICloudUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;

/**
 * 文件上传服务
 *
 * @author liaowen
 * @date 2024/11/12 15:23
 */
@Slf4j
@Service
public class CloudUploadServiceImpl implements ICloudUploadService {

    @Autowired
    private CloudConfig cloudConfig;

    /**
     * 本地文件url上传到oss
     *
     * @param localFileUrl 例如：/2024/11/12/6_20241112144703A001.jpg
     * @return 例如：https://oss.whhcr.com/wwq/cloud/1731395991455.jpg
     */
    @Override
    public String uploadToOss(String localFileUrl, String ossTargetPath) {
        try {
            if (localFileUrl.contains(Constants.RESOURCE_PREFIX)) {
                String[] split = localFileUrl.split(Constants.RESOURCE_PREFIX);
                localFileUrl = split[1];
            }
            String substring = localFileUrl;
            String type = substring.substring(substring.lastIndexOf(".") + 1);
            File file = new File(cloudConfig.getBaseDir() + substring);
            FileInputStream fileInputStream = new FileInputStream(file);
            localFileUrl = OssUtil.INSTANCE.upload(fileInputStream, "wwq/cloud/file/" + System.currentTimeMillis() + "." + type);
            return localFileUrl;
        } catch (Exception e) {
            log.error("本地文件url上传到oss失败：", e);
            return localFileUrl;
        }
    }


    /**
     * 本地文件全路径上传到oss
     *
     * @param localAbsFileName 例如：D:/ruoyi/uploadPath/2024/11/12/6_20241112144703A001.jpg
     * @param ossTargetPath    存储到oss的哪个目录，例如 wwq/cloud/file/
     * @return 例如：https://oss.whhcr.com/wwq/cloud/1731395991455.jpg
     */
    @Override
    public String uploadAbsFileToOss(String localAbsFileName, String ossTargetPath) {
        try {
            File file = new File(localAbsFileName);
            String type = localAbsFileName.substring(localAbsFileName.lastIndexOf(".") + 1);
            FileInputStream fileInputStream = new FileInputStream(file);
            localAbsFileName = OssUtil.INSTANCE.upload(fileInputStream, ossTargetPath + System.currentTimeMillis() + "." + type);
            return localAbsFileName;
        } catch (Exception e) {
            log.error("本地文件url上传到oss失败：", e);
            return localAbsFileName;
        }
    }

}
